<?php

namespace App\Admin\Controllers\Circle;

use App\Admin\Actions\Extensions\NavigaterUrlButton;
use App\Admin\Actions\Grid\CircleAction;
use App\Admin\Renderable\IconRender;
use App\Admin\Repositories\Circle\WxCircle;
use App\Jobs\UpdateCircleInfoJob;
use App\Models\User\WxUser;
use App\Models\WxIcon;
use App\Models\WxPlate;
use App\Models\WxTenant;
use App\Wen\Utils\AdminUtils;
use App\Wen\Utils\Settings;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Support\Facades\Cache;

class WxCircleController extends AdminController
{
    protected $tenants_arr = null;
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        global $__MINI_GLOBAL_TENANT_ID__;
        if($this->tenants_arr === null){
            $tenant_arr_ = [
                '-1' => '全域'
            ];
            if($__MINI_GLOBAL_TENANT_ID__ === 0){
                $tenant_arr = WxTenant::orderBy('order', 'desc')->pluck('name', 'tenant_id')->toArray();
            }else{
                $tenant_arr = WxTenant::where('tenant_id', $__MINI_GLOBAL_TENANT_ID__)->orderBy('order', 'desc')->pluck('name', 'tenant_id')->toArray();
            }
            foreach ($tenant_arr as $key => $val){
                $tenant_arr_[$key.''] = $val;
            }

            $this->tenants_arr = $tenant_arr_;
        }
        return Grid::make(new WxCircle(['wxPlate','wxUser']), function (Grid $grid) {
            // tenant_id代表在哪个分站创建 tenant_show代表希望展现在哪个分站
            global $__MINI_GLOBAL_TENANT_ID__;
            if($__MINI_GLOBAL_TENANT_ID__ > 0){
                $grid->model()->where('tenant_id', '=', $__MINI_GLOBAL_TENANT_ID__)->where('tenant_show', $__MINI_GLOBAL_TENANT_ID__);
            }
            $grid->simplePaginate();
            $grid->model()->orderBy('id', 'desc');
            $grid->quickSearch(['circle_name', 'circle_introduce', 'wxUser.user_name'])->placeholder('搜索圈子名称，介绍，圈主名字...')->width(35);
            $grid->column('id');
            $grid->column('owers', env('circle_user_call', '圈主'))->display(function ($v) {
                if($this->ower['user_avatar'] ?? ''){
                    return '<img src="' . ($this->ower['user_avatar'] ?? Settings::get('img_default', 'https://img.mini.minisns.cn/icons/dafault.png'))  . '"  style="border-radius:50px;width:30px;" />';
                }
                return '';
            })->width('50px');
            $grid->column('ower', ' ')->display(function ($v) {
                if($v && $v['user_name']){
                    return '<a target="_blank" href="'.admin_url('users?id='.$v['id']).'">'.$v['user_name'].'</a>' ?? '用户已删除';
                }
                return '';
            })->width('100px');
            $grid->column('circle_name');
            $grid->column('sort')->editable()->sortable();
            $grid->column('list_style')->select([0=>'跟随全局', 1=>'列表式', 2=>'瀑布流']);
            if($__MINI_GLOBAL_TENANT_ID__ === 0){
                $grid->column('tenant_show', '展示分站&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')->select($this->tenants_arr);
            }else{

            }
            $grid->column('circle_introduce')->sortable()->limit(9);
            $grid->column('head_portrait')->image('','80');
            $grid->column('background_maps')->image('','80');
            $grid->column('wxPlate.plate_name')->label('default');
            $grid->column('is_top_recommend')->switch()->sortable();
            $grid->column('is_hot')->switch()->sortable();
            $grid->column('circle_state')->using([0=>'审核中',1=>'审核通过',2=>'驳回'])->label([
                0=>'red',
                1=>'green',
                2=>'default'
            ])->sortable();
            $grid->column('created_at')->sortable();
            $grid->filter(function (Grid\Filter $filter) {
                $filter->like('circle_name');
                $filter->equal('circle_state')->select([0=>'审核中',1=>'审核通过',2=>'驳回']);
            });
//            $grid->disableCreateButton();
            // 禁用详情按钮
//            $grid->disableViewButton();
//            $grid->disableBatchDelete();
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->append((new CircleAction())->setKey($this->id));
            });

            $grid->tools([
                new NavigaterUrlButton('circle_tag', '', '圈子话题')
            ]);

            if($__MINI_GLOBAL_TENANT_ID__ === 0){
                $grid->header(function ($collection) {
                    return '<div style="background-color: powderblue;color: #414750;padding: 10px;border-radius: 5px;display: inline-block;margin-top: 20px;">圈子分为<b style="color: red">全站圈子</b>和<b style="color: red">分站圈子</b>。全站圈子：可在所有分站展示，有“仅看本站”的开关，在<b>所有圈子</b>里唯一。分站圈子：仅在某个分站展示，没有“仅看本站”的开关，仅在当前分站唯一</div>';
                });
            }

        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new WxCircle(), function (Show $show) {
            $show->field('id');
            $show->field('list_style');
            $show->field('tenant_show');
            $show->field('circle_name');
            $show->field('circle_introduce');
            $show->field('head_portrait');
            $show->field('background_maps');
            $show->field('plate_id');
            $show->field('user_id');
            $show->field('is_top_recommend');
            $show->field('is_hot');
            $show->field('circle_state');
            $show->field('tenant_id');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        global $__MINI_GLOBAL_TENANT_ID__;
        if($this->tenants_arr === null){
            $tenant_arr_ = [
                '-1' => '全域'
            ];
            if($__MINI_GLOBAL_TENANT_ID__ === 0){
                $tenant_arr = WxTenant::orderBy('order', 'desc')->pluck('name', 'tenant_id')->toArray();
            }else{
                $tenant_arr = WxTenant::where('tenant_id', $__MINI_GLOBAL_TENANT_ID__)->orderBy('order', 'desc')->pluck('name', 'tenant_id')->toArray();
            }
            foreach ($tenant_arr as $key => $val){
                $tenant_arr_[$key.''] = $val;
            }

            $this->tenants_arr = $tenant_arr_;
        }
        return Form::make(new WxCircle(), function (Form $form) {
            global $__MINI_GLOBAL_TENANT_ID__;
            $circle_id = $form->model()->id;
            $old_circle_name = $form->model()->circle_name;
            $form->display('id');
            $form->text('circle_name')->required();
            $form->number('sort');
            $form->radio('list_style')->options([0=>'跟随全局', 1=>'列表式', 2=>'瀑布流'])->default(Settings::get('app_circle_list_style', 0, true));
            if($__MINI_GLOBAL_TENANT_ID__ === 0){
                $form->select('tenant_show')->options($this->tenants_arr)->default(-1)->required();
            }
            $form->text('circle_introduce')->required();
            $form->image('head_portrait')->url('files/uploads')->uniqueName()->autoUpload()->required();
            $form->image('background_maps')->help('<a href="https://img.mini.minisns.cn/images/topci/bg.jpg" target="_blank">点击下载默认图</a>')->url('files/uploads')->uniqueName()->autoUpload()->required()->default(Settings::get('img_default_circle_bg', ''));
            $form->select('plate_id')->options(WxPlate::pluck('plate_name', 'id'))->required();

            $form->select('user_id', env('circle_user_call', '圈主'))->options(function ($id) {
                if($id){
                    $user = WxUser::find($id);
                    if ($user) {
                        return [$user->id => $user->user_name];
                    }
                }
            })->ajax('select/users');

            $form->multipleSelectTable('square_list', '格子菜单')
                ->title('图标库')
                ->max(100)
                ->from(IconRender::make())
                ->model(WxIcon::class, 'id', 'name', 'selectTable:WxCircleController:circle_square_list')
                ->help('各个圈子自己额外的格子菜单， <a href="'.admin_url('settings/icons').'" target="_blank">管理图标库>></a><a href="https://doc.minisns.cn/doc/70/" target="_blank" style="color: red;">（ps：如何控制顺序?）&nbsp;</a>')
                ->saveAsJson();

            $form->switch('is_top_recommend');
            $form->switch('is_hot');
            $form->switch('is_publish_admin');
            $form->radio('is_city_select')->options([0=>'关闭',1=>'开启'])->default(0);
            $form->radio('is_tenant_select')->help('仅[展示分站为全域]时起作用，也就是只有全站圈子会显示这个按钮，自然也只有全站圈子可以关闭')->options([0=>'关闭',1=>'开启'])->default(0);
            $form->radio('circle_state')->options([0=>'审核中',1=>'审核通过',2=>'驳回'])->default(1);

            global $__MINI_GLOBAL_TENANT_ID__;
            if($__MINI_GLOBAL_TENANT_ID__ > 0){
                $form->text('tenant_id', '本站分应用id')->help('忽略这个配置')->default($__MINI_GLOBAL_TENANT_ID__);
            }

            $form->saving(function (Form $form){
                global $__MINI_GLOBAL_TENANT_ID__;
                if($__MINI_GLOBAL_TENANT_ID__ > 0 && $form->getKey() > 0){
                    if(\App\Models\Circle\WxCircle::where('id', $form->getKey())->value('tenant_id') != $__MINI_GLOBAL_TENANT_ID__){
                        return $form->response()->error('权限不足，不可以修改其他分站对象');
                    }
                }
                if($form->input('user_id') > 0){
                    $form->user_id = (int)($form->input('user_id'));
                }
                $form->tenant_id = $__MINI_GLOBAL_TENANT_ID__;
                if($__MINI_GLOBAL_TENANT_ID__ > 0){
                    $form->deleteInput('tenant_show');
                }
                $form->input('square_list', AdminUtils::_multipleSelectTable_order_process('selectTable:WxCircleController:circle_square_list', $form->input('square_list')));
            });

            $form->saved(function (Form $form) use ($old_circle_name, $circle_id){
                $data = $form->updates();
                // 淘汰，采用模型监测
//                if(isset($data['circle_name']) && $old_circle_name != _array_key($data, 'circle_name', '') ){
//                    UpdateCircleInfoJob::dispatch($circle_id);
//                }
                Cache::forget('circle:list:style:'.$circle_id);
            });

            $form->deleting(function (Form $form){
                global $__MINI_GLOBAL_TENANT_ID__;
                if($__MINI_GLOBAL_TENANT_ID__ > 0){
                    if(\App\Models\Circle\WxCircle::where('id', $form->getKey())->value('tenant_id') != $__MINI_GLOBAL_TENANT_ID__){
                        return $form->response()->error('权限不足，不可以删除其他分站对象');
                    }
                }
            });

        });
    }

}
